package com.czl.module_service.extension

import android.view.View
import android.view.ViewGroup
import com.chad.library.adapter.base.BaseQuickAdapter
import com.cooltechworks.views.shimmer.ShimmerRecyclerView
import com.czl.base.R
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseFragment
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.ToastHelper.showErrorToast
import com.scwang.smart.refresh.layout.SmartRefreshLayout

/**
 * @author by xubin,
 * @date on 2022/1/19.
 * PS: Not easy to write code, please indicate.
 */

fun <T> BaseFragment<*, *>.loadCompletedData(
    hasNextPage: Boolean?,
    isFirstPage: Boolean?,
    loadSuccess: Boolean,
    total: Int?,
    data: List<T>?,
    mAdapter: BaseQuickAdapter<T, *>,
    ryCommon: ShimmerRecyclerView,
    smartCommon: SmartRefreshLayout,
) {
    var nextPage = hasNextPage
    total?.let {
        if (it == data?.size) {
            nextPage = false
        }
    }
    if (!loadSuccess) {
        if (isFirstPage == true) {
            showErrorStatePage()
        }
        smartCommon.finishRefresh(false)
        smartCommon.finishLoadMore(false)
        return
    }
    showSuccessStatePage()
    nextPage?.let {
        if (!it) {
            smartCommon.finishLoadMoreWithNoMoreData()
        } else {
            smartCommon.finishLoadMore(true)
        }
    }
    if (isFirstPage == true) {
        smartCommon.finishRefresh(true)
        ryCommon.hideShimmerAdapter()
        if (!mAdapter.hasEmptyView() && !mAdapter.hasHeaderLayout()) {
            val emptyView = View.inflate(context, R.layout.common_empty_layout, null)
            emptyView.findViewById<ViewGroup>(R.id.ll_empty).setOnClickListener {
                smartCommon.autoRefresh()
            }
            mAdapter.setEmptyView(emptyView)
        }
        mAdapter.setList(data)
        ryCommon.smoothScrollToPosition(0)
        return
    }
    data?.let { mAdapter.addData(it) }
}

fun <T : BaseBean<V>, V> ApiSubscriberHelper<*>.result(
    t: T,
    event: SingleLiveEvent<V>,
    block: ((Boolean) -> Unit)? = null
) {
    if (t.errorCode != 0) {
        showErrorToast(t.msg)
        event.postValue(null)
        block?.let { it(false) }
    } else {
        event.postValue(t.data)
        block?.let { it(false) }
    }
}